package com.waltercedric.java.joomla.gridupdater;

import java.io.File;
import java.util.List;

import com.waltercedric.java.joomla.gridupdater.protocol.ProtocolFactory;
import com.waltercedric.java.joomla.gridupdater.protocol.SSH;
import com.waltercedric.java.joomla.gridupdater.protocol.SiteConnector;
import com.waltercedric.java.joomla.gridupdater.repository.Repository;
import com.waltercedric.java.joomla.gridupdater.vo.Site;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Repository repository = new Repository();

		List<Site> sitesList = Configuration.getSitesList();
		for (Site site : sitesList) {
			System.out.println("Site is " + site);

			SiteConnector siteConnector = ProtocolFactory.getSiteConnector(site);
			siteConnector.connect();
			
			JoomlaDetector joomlaDetector = new JoomlaDetector(siteConnector);
			
			double remoteJoomlaMainVersion = joomlaDetector.getMainVersion();		
			int repositoryLatestPatchVersion = repository.getLatestPatchVersion(remoteJoomlaMainVersion);
			int remoteJoomlaPatchVersion = joomlaDetector.getPatchVersion();
			
			if (remoteJoomlaPatchVersion < repositoryLatestPatchVersion) {
				
				File latestPatchVersionFile = repository.getLatestPatchVersionFile(remoteJoomlaMainVersion, repositoryLatestPatchVersion);
				File joomlaReferenceFileReference = repository.getJoomlaReferenceFile(remoteJoomlaMainVersion, remoteJoomlaPatchVersion);
				
				FileTamperingComparator fileTamperingComparator = new FileTamperingComparator(siteConnector);
				List<String> filesAltered = fileTamperingComparator.check(latestPatchVersionFile, joomlaReferenceFileReference);
				if (filesAltered.isEmpty()) {
					JoomlaUpdater joomlaUpdater = new JoomlaUpdater (siteConnector);
					
					try {
						joomlaUpdater.update(latestPatchVersionFile);
					} catch (Exception e) {
						joomlaUpdater.rollback();
					}
					
					
					
					
				}
			}
			
			
			
		}

	}
}
